//
//  zcVideoEntrance.m
//  智能控制系统
//
//  Created by Rankin on 15/12/2.
//
//
#define NOTNULL(__POINTER) __POINTER ==nil||__POINTER==[NSNull null]? @"" : __POINTER

#import "ZcVideo.h"

@implementation ZcVideo
HKSDeviceClient *client;
- (void)pluginInitialize{
 
    [self initServer];
    
    self.searchDevices = [[NSMutableArray alloc]init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
}

//初始化镜头服务
- (void)initServer{
    [[HKSServerClient shareClient] initClient];
    NSString *tempServer = @"app.umeye.cn:8300";
    NSArray *tempServers = [tempServer componentsSeparatedByString:@":"];
    if (tempServers.count == 2) {
        [[HKSServerClient shareClient] setServerConnWithParam:[tempServers objectAtIndex:0] port:[[tempServers objectAtIndex:1] intValue] clientCustomFlag:@"my_umeyeprofessional"];
        [[HKSServerClient shareClient]startUMIDServer];
    }
    
    //免登录模式
  [HKSServerClient shareClient].logEnable = YES;  //调试模式打开
//    [HKSServerClient shareClient].stringEncoding = NSUTF8StringEncoding;
    
    
    
//废弃方法
//    int state = [[HKSServerClient shareClient] loginServerWithUser:@"" password:@"" type:3];
//    if (state == HKS_NPC_D_MPI_MON_ERROR_CONNECT_FAIL) {
//        state = [[HKSServerClient shareClient] loginServerWithUser:@"" password:@"" type:3];
//    }
//废弃方法
}



- (void)showVideoView:(CDVInvokedUrlCommand*)command{
    if([[command arguments]count] < 4){
        NSLog(@"参数错误");
        return;
    }
    NSString *umid = [command.arguments objectAtIndex:0];
    NSString *userId = [command.arguments objectAtIndex:1];
    NSString *pwd = NOTNULL([command.arguments objectAtIndex:2]);
    int channelNo = [[command.arguments objectAtIndex:3]intValue];
    
//    UIViewController* viewController = [[zcVideoViewController alloc]initWithUmid:@"xmksitfcfdyx" deviceUserId:@"admin" devicePassword:@""];
    UIViewController* viewController = [[zcVideoViewController alloc]initWithUmid:umid
                                                                     deviceUserId:userId
                                                                   devicePassword:pwd
                                                                        channelNo:channelNo];
    
//    viewController = [[VideoPlayViewController alloc]initWithNibName:@"VideoPlayView" bundle:[NSBundle mainBundle]];
    
    
//    viewController =[[zcVideoViewController alloc]initWithNibName:@"videoView" bundle:[NSBundle mainBundle]];
    
//    [self.viewController.view addSubview:viewController.view];
//    [self.viewController addChildViewController:viewController];
//    self.viewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//    [self.viewController
//     presentViewController:viewController
//     animated:YES completion:nil
//     ];
//    UINavigationController *nav = [[UINavigationController alloc]init];
//    [self.viewController addChildViewController:nav];
//    [nav pushViewController:viewController animated:YES];
    
    
    //方法1:
    viewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    //childBrowser.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    //childBrowser.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    //childBrowser.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    
    [self.viewController presentViewController:viewController animated:YES completion:nil];
    
//    self.viewController.hidesBottomBarWhenPushed = true;
//    [self.viewController.navigationController pushViewController:viewController animated:YES];
    
//    [self.viewController.view bringSubviewToFront:viewController.view];
    
}

-(void)changePwd:(CDVInvokedUrlCommand*)command{
    if([[command arguments]count] < 4){
        NSLog(@"参数错误");
        return;
    }
    NSString *umid = [command.arguments objectAtIndex:0];
    NSString *userId = [command.arguments objectAtIndex:1];
    NSString *pwd = NOTNULL([command.arguments objectAtIndex:2]);
    NSString *newPwd = NOTNULL([command.arguments objectAtIndex:3]);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        HKSDeviceClient *clinet = [[HKSDeviceClient alloc]init];
        [clinet setDeviceConnParam:@"app.umeye.cn"
                        serverPort:8300
                        deviceUMID: umid
                      deviceUserID:userId
                    devicePassword:pwd
                     deviceChannel:0
                      deviceStream:1
                      deviceVendor:-1];
        
        int ret = HKS_NPC_D_MPI_MON_ERROR_SUC;
        ret = [clinet setDeviceNewPassword:newPwd];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret == HKS_NPC_D_MPI_MON_ERROR_SUC ) {
                CDVPluginResult* cdvRes = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
                [self.commandDelegate sendPluginResult:cdvRes callbackId:command.callbackId];
            }else{
                CDVPluginResult* cdvRes = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                [self.commandDelegate sendPluginResult:cdvRes callbackId:command.callbackId];
            }
        });
        
    });
}

-(void)search:(CDVInvokedUrlCommand*)command{
    self.callbackId = command.callbackId;
    [self starSearchDevice];
}

- (void)playVideo:(CDVInvokedUrlCommand*)command{
    if([[command arguments]count] < 5){
        NSLog(@"参数错误");
        return;
    }
    NSString *umid = [command.arguments objectAtIndex:0];
    NSString *userId = [command.arguments objectAtIndex:1];
    NSString *pwd = NOTNULL([command.arguments objectAtIndex:2]);
    NSDictionary *recFileDic = [command.arguments objectAtIndex:4];
    int channelNo = [[command.arguments objectAtIndex:3]intValue];
    NSString *recfile = NOTNULL([recFileDic objectForKey:@"fileName"]);
    
    UIViewController* vc = [[ZcVideoPreviewViewController alloc]initWithUmid:umid deviceUserId:userId devicePassword:pwd recfile:[self getRecFile:recfile] channelNo:channelNo];
    
    [vc setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self.viewController presentViewController:vc animated:YES completion:nil];
}

-(void)connect:(CDVInvokedUrlCommand*)command {
    if([[command arguments]count] < 4){
        NSLog(@"参数错误");
        return;
    }
    NSString *umid = [command.arguments objectAtIndex:0];
    NSString *userId = [command.arguments objectAtIndex:1];
    NSString *pwd = NOTNULL([command.arguments objectAtIndex:2]);
    NSArray *data = [command.arguments objectAtIndex:3];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (client==nil) {
            client = [[HKSDeviceClient alloc]init];
        }
        
        if (client.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_STOP
            || client.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_READY) {
            [client setDeviceConnParam:@"app.umeye.cn"
                            serverPort:8300
                            deviceUMID:umid
                          deviceUserID:userId
                        devicePassword:pwd
                         deviceChannel:0
                          deviceStream:1
                          deviceVendor:-1];
        }
        char *sendDatas = malloc(data.count*sizeof(sendDatas));
        for (int i=0; i<data.count; i++) {
            sendDatas[i] = [[data objectAtIndex:i]intValue];
        }
        NSLog(@"%@",[NSData dataWithBytes:sendDatas length:data.count]);
        
        //发送之前需要调用打开串口接口
        int a = [client serialPortsComOpen:1 prot:2 baudRate:2400 dataBit:8 stopBit:1 checkBit:1];
        
        //打开串口以后，可以一直调用发送接口。
        a = [client serialPortsComSend:1 prot:2 sendDataBuf:(unsigned char *)sendDatas sendDataBufLen:data.count];
        
        //不需要发送接口以后，需要调用该接口进行关闭串口
        a = [client serialPortsComClose:1 prot:2];
    });
}

-(void)searchVideo:(CDVInvokedUrlCommand*)command{
    if([[command arguments]count] < 7){
        NSLog(@"参数错误");
        return;
    }
    
    self.searchHistoryCallbackId = command.callbackId;
    
    NSString *umid = [command.arguments objectAtIndex:0];
    NSString *userId = [command.arguments objectAtIndex:1];
    NSString *pwd = NOTNULL([command.arguments objectAtIndex:2]);
    int channelNo = [[command.arguments objectAtIndex:3]intValue];
    NSDictionary *startTime = [command.arguments objectAtIndex:4];
    NSDictionary *endTime = [command.arguments objectAtIndex:5];
    NSInteger recordType = [[command.arguments objectAtIndex:6]intValue];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        HKSDeviceClient *clinet = [[HKSDeviceClient alloc]init];
        [clinet setDeviceConnParam:@"app.umeye.cn"
                        serverPort:8300
                        deviceUMID: umid
                      deviceUserID:userId
                    devicePassword:pwd
                     deviceChannel:channelNo
                      deviceStream:1
                      deviceVendor:-1];
        
        NSMutableArray *retArr = [[NSMutableArray alloc]init];
        
        int ret = HKS_NPC_D_MPI_MON_ERROR_SUC;
        ret =[clinet searchRecFile:[self getDateTime:startTime]
                               end:[self getDateTime:endTime]
                          fileType:[self getFileType:recordType] outFileList:retArr];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog([NSString stringWithFormat:@"搜索返回的状态码为：%d",ret ]);
            if(ret == HKS_NPC_D_MPI_MON_ERROR_SUC){
                if(retArr.count>0){
                    CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[self getArrFromRecArr:retArr]];
                    self.recfiles = retArr;
                    [self.commandDelegate sendPluginResult:res callbackId:self.searchHistoryCallbackId];
                    return ;
                }
            }
            CDVPluginResult *errRes = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
            [self.commandDelegate sendPluginResult:errRes callbackId:self.searchHistoryCallbackId];
        });
    });
}

- (NSArray* )getArrFromRecArr:(NSArray*)recArr{
    NSMutableArray* retArr = [[NSMutableArray alloc]init];
    for (int i=0; i<recArr.count; i++) {
       [retArr addObject: [self getDicFromRecFile:recArr[i]]];
    }
    return retArr;
}

- (NSDictionary* )getDicFromRecFile:(HKSRecFile*)recfile{
//    NSMutableDictionary* retDic = [[NSMutableDictionary alloc]init];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:recfile.startTime.year forKey:@"syear"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
//    [retDic setObject:NOTNULL(recfile.fileName) forKey:@"fileName"];
    
    
    return  [[NSDictionary alloc]initWithObjectsAndKeys:
                            NOTNULL(recfile.fileName),@"fileName",
                            NOTNULL([[NSNumber alloc]initWithShort: recfile.startTime.year]),@"syear",
                            NOTNULL([[NSNumber alloc]initWithShort:recfile.startTime.month ]),@"smonth",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.startTime.hour]),@"shour",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.startTime.minute]),@"sminute",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.startTime.second]),@"ssecond",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.startTime.day]),@"sday",
                            NOTNULL([[NSNumber alloc]initWithShort: recfile.endTime.year]),@"eyear",
                            NOTNULL([[NSNumber alloc]initWithShort: recfile.endTime.month]),@"emonth",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.endTime.day]),@"eday",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.endTime.hour]),@"ehour",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.endTime.minute]),@"eminute",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.endTime.second]),@"esecond",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.fileSize]),@"nFileSize",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.fileType]),@"nFileType",
                            NOTNULL([[NSNumber alloc]initWithLong:recfile.param1]) ,@"nParam1",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.param2]),@"nParam2",
                            NOTNULL(recfile.devId),@"devId",
                            NOTNULL([[NSNumber alloc]initWithInt: recfile.recTimeLen]),@"recTimeLen",
             nil];
    
}


- (HKSRecFile*)getRecFile:(NSString*)filename  {
    for (int i=0; i<self.recfiles.count; i++) {
        HKSRecFile* file = self.recfiles[i];
        if([file.fileName isEqualToString: filename])
            return file;
    }
    return nil;
}

- (Date_Time)getDateTime:(NSDictionary*)time{
    Date_Time dt ;
    dt.year = [[time objectForKey:@"year"]integerValue];
    dt.month = [[time objectForKey:@"month"]integerValue];
    dt.day = [[time objectForKey:@"day"]integerValue];
    dt.hour = [[time objectForKey:@"hour"]integerValue];
    dt.minute = [[time objectForKey:@"minute"]integerValue];
    dt.second = [[time objectForKey:@"second"]integerValue];
    dt.minsecond = 0;
    
    return dt;
}



- (int)getFileType:(int)recordType{
    int fileType;
    switch (recordType) {
        case 255:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_ALL;
            break;
        case 1:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_GENERAL;
            break;
        case 2:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_ALARM;
            break;
        case 4:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_MALUAL;
            break;
        case 8:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_PROBE;
            break;
            
        default:
            fileType = HKS_NPC_D_MON_REC_FILE_TYPE_ALL;
            break;
    }
    return fileType;
}

- (void)starSearchDevice{
    dispatch_async(dispatch_get_main_queue(),^{
        HK_TIMER_NULL(_updateSearchDataTimer);
        [[HKSServerClient shareClient] startSearchDevice];
        dispatch_async(dispatch_get_main_queue(), ^{
            _updateSearchCount = 0;
            if (!_updateSearchDataTimer) {
                _updateSearchDataTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateSearchData) userInfo:nil repeats:YES];
            }
            
        });
        
        
    });
}

- (void)updateSearchData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
        _updateSearchCount++;
        int ret = [[HKSServerClient shareClient] getSearchDevTable:_searchDevices];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_updateSearchCount > 8 || self.searchDevices.count > 0 || ret != HKS_NPC_D_MPI_MON_ERROR_SUC) {
                //要先停掉搜索
                [[HKSServerClient shareClient] stopSearchDevice];
                HK_TIMER_NULL(_updateSearchDataTimer);
                
                //如果查不到设备，返回失败的结果
                if(ret != HKS_NPC_D_MPI_MON_ERROR_SUC||self.searchDevices.count==0){
                    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
                    
                    [self.commandDelegate sendPluginResult:result callbackId:[self callbackId]];

                    return;
                }

                TreeListItem *tl =[self getDeviceItemFromSearchItem:_searchDevices[0]];
                int ret = [[HKSServerClient shareClient] addServerDevInfo:tl];
                if (ret != HKS_NPC_D_MPI_MON_ERROR_SUC) {
                    //如果失败，进行第二次尝试
                    ret = [[HKSServerClient shareClient] addServerDevInfo:tl];
                }
                NSMutableArray *tempDevices = [[NSMutableArray alloc] init];
                [[HKSServerClient shareClient] treeListDataAtIndex:0 deviceList:tempDevices];

                NSMutableArray *retArr = [[NSMutableArray alloc]init];

                for(HKSDeviceSearchItem *s in _searchDevices){
                    NSString *deviceUMID = [[NSString alloc ]initWithString: s.sDevId?s.sDevId:[NSNull null]];
                    NSString *deviceUserId = [[NSString alloc ]initWithString: s.sDevUserName?s.sDevUserName:[NSNull null]];
                    
                    NSString *deviceIp = NOTNULL(s.sDevAddress);
                    
                    NSString *deviceChannel = [NSString stringWithFormat:@"%d",s.usChNum];
                    
                    NSString *deviceName =  NOTNULL(s.sDevModel);
                    
                    NSDictionary *retDic = [[NSDictionary alloc]initWithObjectsAndKeys:
                                                deviceUMID, @"deviceUmid",
                                                deviceUserId,@"deviceUserID",
                                                @"",@"devicePassword",
                                                deviceName,@"deviceName",
                                                deviceChannel,@"deviceChannel",
                                                deviceIp,@"deviceIp", nil
                                            ];
                    [retArr addObject:retDic];
                }

                CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:retArr];
                
                [self.commandDelegate sendPluginResult:result callbackId:[self callbackId]];

            }
        });
    });
    
}

-(TreeListItem*)getDeviceItemFromSearchItem:(HKSDeviceSearchItem*)searchItem{
    
    
    HKSDeviceSearchAdapterItem *tempAdapterItem = [searchItem.tAdapterTable objectAtIndex:0];
    TreeListItem *item = [[TreeListItem alloc] init];
    
    
    item.iNodeType = HKS_NPC_D_MPI_MON_DEV_NODE_TYPE_CAMERA;
    
    item.dwParentNodeId = 0;
    item.iConnMode = HKS_NPC_D_MON_CONN_MODE_CLOUD;
    item.sNodeName = searchItem.sDevModel;
    item.iChannel = item.iNodeType == HKS_NPC_D_MPI_MON_DEV_NODE_TYPE_CAMERA ? 0 : searchItem.usChNum;
    if (item.iConnMode == HKS_NPC_D_MON_CONN_MODE_P2P) {
        item.iVendorId = HKS_NPC_D_MON_VENDOR_ID_UMSP;
    }
    item.iPort = searchItem.iDevPort;
    item.sUserId = searchItem.sDevUserName;
    item.sUserPwd = @""; //todo 密码
    item.sDeviceId = searchItem.sDevId;
    item.sAddress = tempAdapterItem.sIpaddr;
    item.iStream = 1;
    item.iChannel = searchItem.usChNum;
    
    //    item.ucNodeKind = 0;
    //    item.ucIfPtz = 1;
    //    item.ucDevState = 1;
    
    return item;
}



//-----------------
-(void)onResume{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"Resum starumidServer");
        [[HKSServerClient shareClient] startUMIDServer];
    });
}

-(void)onPause{
    NSLog(@"Stop umid");
     [[HKSServerClient shareClient] stopUMIDServer];
}



@end
